package com.jing.system.tags.loadresource;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

import org.apache.log4j.Logger;

/**
 * 加载资源的类
 * @author jing.yue
 * @version 1.0
 * @since 2012-10-12
 */
public class LoadResource {

	private static Logger log = Logger.getLogger(LoadResource.class);

	/** 默认读取路径 */
	private static final String LOAD_RESOURCE_URL = "loadresource.properties";

	/**
	 * 初始化资源信息
	 * @param loadResourceUrl	加载公用配置的资源文件路径
	 * @return
	 */
	public static void initLoadResource(String loadResourceUrl) {
		initLoadResource(loadResourceUrl, null);
	}

	/**
	 * 初始化资源信息[有版本号]
	 * @param loadResourceUrl	加载公用配置的资源文件路径
	 * @param version			版本号
	 * @return
	 */
	public static void initLoadResource(String loadResourceUrl, String version) {
		Properties properties = new Properties();
		try {
			properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(loadResourceUrl));

			if(loadResourceUrl == null) {
				loadResourceUrl = LOAD_RESOURCE_URL;
			}
			if(version == null) {
				version = "";
			}
			else {
				version = "?version=" + version;
			}

			Enumeration<Object> en = properties.keys();
            while(en.hasMoreElements()){
                String name = en.nextElement().toString();
                String path = properties.getProperty(name) + version;
                if(path.lastIndexOf(".js") != -1) {
                    JsTag.jsMap.put(name, path);
                }
                else if(path.lastIndexOf(".css") != -1) {
                	CssTag.cssMap.put(name, path);
                }
            }
            log.info("初始化资源信息: SUCCESS");
		}
		catch (FileNotFoundException e) {
			log.error("读取属性文件: 失败\t原因: 文件路径错误或者文件不存在");
		}
		catch (IOException e) {
			log.error("装载文件: 失败\t原因: " + e.getMessage());
		}
		catch (Exception e) {
			log.error("未知异常\t原因: " + e.getMessage());
		}
	}

	/**
	 * 获取需要调用的集合
	 * @return
	 */
	public static List<String> getLibsArr(String libs) {
		List<String> libList = new ArrayList<String>();
		for (String lib : libs.split(",")) {
			libList.add(lib);
		}
		return libList;
	}
}
